package Session;

import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import Agent.Agent;
import Agent.ObjectAgent;
import Exception.ExceptionVM;
import SLA.SLA;
import Server.Server;

public class Session implements Runnable{
	private ArrayList<ObjectAgent> agents;
	private Server s;
	private int index=0;
	private static final Logger LOG = Logger.getLogger(Server.class.getName());

	public Session(Server s) throws SecurityException, IOException {
		agents = new ArrayList<ObjectAgent>();
		this.s = s;
		index = -1;
		Handler file = new FileHandler("Logger.txt");
		file.setLevel(Level.ALL);
		LOG.addHandler(file);
		LOG.setUseParentHandlers(false);
	}

	public ArrayList<ObjectAgent> getAgents() {
		return agents;
	}

	public void addAgent(ObjectAgent a) {
		agents.add(a);
	}

	public float calculateProfit() throws AccessException, RemoteException, NotBoundException{
		Remote obj; 
		SLA sla;
		float profit = 0;
		for(int j=0;j<=agents.size();j++){
			obj = LocateRegistry.getRegistry(agents.get(j).getIp(),agents.get(j).getPort()).lookup(agents.get(j).getAgentName());
			sla = ((Agent) obj).getSla();
			profit += (sla.getValueOfService() - ( ((Agent) obj).getTuplesToReturn()*sla.getCostTuple() + 
							sla.getCostMonitoring()*((Agent) obj).getTimeMonitoring() + sla.getMachineCost() ) );
		}
		return profit;
	}

	public void run(){
		Remote obj = null;
		ObjectAgent simpleAgent = null;
		
		int i = 0;
		index++;		
		
		try {
			simpleAgent = agents.get(index);
			obj = LocateRegistry.getRegistry(simpleAgent.getIp(),simpleAgent.getPort()).lookup(simpleAgent.getAgentName());
			((Agent) obj).query();
		
		} catch (ExceptionVM e) {
			System.out.println(e.getMessage());			
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}//run
	
}
